package svc

import (
	"database/sql"

	"mall/common/modelx"
	"mall/service/product/rpc/productclient"
	"mall/service/promotion/repository"
	"mall/service/promotion/rpc/internal/config"

	"github.com/zeromicro/go-queue/kq"
	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/core/stores/redis"
	"github.com/zeromicro/go-zero/zrpc"
)

type ServiceContext struct {
	Config config.Config

	BizRedis                 *redis.Redis
	KqClient                 *kq.Pusher
	KqDistributePointsClient *kq.Pusher

	DB             *sql.DB
	Activity       repository.ActivityRepository
	CouponTemplate repository.CouponTemplateRepository
	Coupon         repository.CouponRepository

	ProductRpc productclient.Product
}

func NewServiceContext(c config.Config) *ServiceContext {
	db, err := modelx.NewMysqlConn(c.Mysql.DataSource)
	if err != nil {
		logx.Must(err)
	}

	rds := redis.MustNewRedis(c.BizRedis)

	return &ServiceContext{
		Config: c,

		BizRedis:                 rds,
		KqClient:                 kq.NewPusher(c.KqConf.Brokers, c.KqConf.Topic),
		KqDistributePointsClient: kq.NewPusher(c.KqDistributePointsConf.Brokers, c.KqDistributePointsConf.Topic),

		DB:             db,
		Activity:       repository.NewActivityRepository(db, c.CacheRedis),
		CouponTemplate: repository.NewCouponTemplateRepository(db, c.CacheRedis),
		Coupon:         repository.NewCouponRepository(db, c.CacheRedis),

		ProductRpc: productclient.NewProduct(zrpc.MustNewClient(c.ProductRpc)),
	}
}
